package com.krause.marinechart.iso8211;

import java.util.ArrayList;


public class Directory implements Constants{
	
	protected ArrayList<FieldDef> fieldDefs;
	
	public Directory (byte[] mDirectoryArray, Leader mLeader)	{
		this(mDirectoryArray, mLeader.sizeFieldLength, mLeader.sizeFieldPos, mLeader.sizeFieldTag);
	}

	public Directory (byte[] mDirectoryArray, int sizeFieldLength, int sizeFieldPos, int sizeFieldTag)	{
		int fieldDefWidth = sizeFieldLength + sizeFieldPos + sizeFieldTag;
		
		fieldDefs = new ArrayList<FieldDef>();
		int marker;
		for (int i = 0; i < (mDirectoryArray.length); i += fieldDefWidth) {
			marker = i;
			if (mDirectoryArray[i] != DDF_FIELD_TERMINATOR) {
				String mFieldTag = new String(mDirectoryArray, marker, sizeFieldTag);
				marker += sizeFieldTag;
				int mFieldLength = Utils.byteToInt(mDirectoryArray, marker, sizeFieldLength);
				marker += sizeFieldLength;
				int mFieldPos = Utils.byteToInt(mDirectoryArray, marker, sizeFieldPos);

				fieldDefs.add(new FieldDef(mFieldTag, mFieldLength, mFieldPos));
				
				Module.sb.append(new String(mFieldTag + mFieldLength + mFieldPos + "\n"));
			} else {
				Module.sb.append('\n');
				break;
			}
		}
	}
	
	protected class FieldDef {
		public String fieldTag;
		public int fieldLength;
		public int fieldPos;
		
		public FieldDef(String fieldTag, int fieldLength, int fieldPos) {
			super();
			this.fieldTag = fieldTag;
			this.fieldLength = fieldLength;
			this.fieldPos = fieldPos;
		}
		
		@Override
		public String toString() {
			return fieldTag + " " + fieldLength + " " + fieldPos;
		}
		
	}

}
